﻿using System;
using System.Linq;
using NDatabase;
using NDatabase.Api;

namespace Infrastructure
{
	public class Person
	{
		public string Name { get; set; }

		public int Money { get; set; }
	}

	public static class MyDataBase
	{

		private static string _myDatabase = "myDb2";

		public static void Save(Person obj, string name)
		{
			//kolla om personen finns, i så fall uppdatera pengarna:

			using (var odb = OdbFactory.Open(_myDatabase))
			{
				IObjectSet<Person> people = odb.Query<Person>().Execute<Person>();

				Person thePerson = null;
				foreach (var person in people)
				{
					if (person.Name == obj.Name)
					{
						thePerson = person;
					}
				}

				if (thePerson != null)
				{
					thePerson.Money = obj.Money;
					odb.Store(obj);
				}
				else
				{
					odb.Store(obj);
					
				}
			}
		}

		public static Person Read(string name)
		{
			using (var odb = OdbFactory.Open(_myDatabase))
			{
				IObjectSet<Person> everything = odb.Query<Person>().Execute<Person>();

				var thePerson =  everything.FirstOrDefault(p => p.Name == name);
				return thePerson;
			}
		}

	}
}
